import triton
import triton.language as tl

from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math

import torch
import torch_npu
from .util import triton_helper_compile, compiled_kernel_list

# fused__safe_softmax_add_eq_masked_fill_4
@triton.jit
def fused_kernel12(in_ptr0, in_ptr1, in_ptr2, out_ptr3, xnumel, rnumel):
    xnumel = 288
    XBLOCK: tl.constexpr = 1
    rnumel = 9
    RBLOCK: tl.constexpr = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = tl.full([1], xoffset, tl.int32)
    xmask = tl.full([RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[:]
    roffset = 0
    rmask = rindex < rnumel
    r2 = rindex
    x3 = xindex
    x0 = xindex % 9
    tmp0 = tl.load(in_ptr0 + (r2 + (9*x3)), rmask, other=0.0)
    tmp7 = tl.load(in_ptr1 + (x0), None, eviction_policy='evict_last')
    tmp12 = tl.load(in_ptr2 + (r2), rmask, eviction_policy='evict_last', other=0.0)
    tmp1 = r2 + ((-1)*x0)
    tmp2 = tl.full([1], 1, tl.int32)
    tmp3 = tmp1 >= tmp2
    tmp4 = -3.4028234663852886e+38
    tmp5 = 0.0
    tmp6 = tl.where(tmp3, tmp4, tmp5)
    tmp8 = r2
    tmp9 = tmp8 > tmp7
    tmp10 = tmp9.to(tl.float32)
    tmp11 = tmp6 * tmp10
    tmp13 = tmp12.to(tl.float32)
    tmp14 = tmp11 + tmp13
    tmp15 = tmp14 == tmp5
    tmp16 = tl.where(tmp15, tmp4, tmp11)
    tmp17 = tmp0 + tmp16
    tmp18 = float("-inf")
    tmp19 = tmp17 == tmp18
    tmp20 = tmp19 == 0
    tmp21 = tmp20.to(tl.int32)
    tmp22 = (tmp21 != 0)
    tmp23 = tl.broadcast_to(tmp22, [RBLOCK])
    tmp25 = tl.where(rmask, tmp23, 0)
    tmp26 = triton_helpers.promote_to_tensor(triton_helpers.any(tmp25, 0))
    tmp27 = tl.broadcast_to(tmp17, [RBLOCK])
    tmp29 = tl.where(rmask, tmp27, float("-inf"))
    tmp30 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp29, 0))
    tmp31 = tmp17 - tmp30
    tmp32 = tl_math.exp(tmp31)
    tmp33 = tl.broadcast_to(tmp32, [RBLOCK])
    tmp35 = tl.where(rmask, tmp33, 0)
    tmp36 = triton_helpers.promote_to_tensor(tl.sum(tmp35, 0))
    tmp37 = tmp26 == 0
    tmp38 = tmp32 / tmp36
    tmp39 = tl.where(tmp37, tmp5, tmp38)
    tl.store(out_ptr3 + (r2 + (9*x3)), tmp39, rmask)

def test_compile_for_fused_kernel12():
    signature = "*fp32,*i32,*i32,*fp32,i32,i32"
    triton_helper_compile(func=fused_kernel12, signature=signature)

compiled_kernel_list["fused_kernel12"] = test_compile_for_fused_kernel12